package stack;

import org.junit.Test;

import java.util.Stack;

/**
 * @className: LeetCode_739
 * @Description: ...
 * @author: kunkun
 * @date: 2025/3/12 22:54
 */
public class LeetCode_394 {

    @Test
    public void test(){
        System.out.println(decodeString("10[leetcode]"));
    }

    public String decodeString(String s) {
        //1. 定义返回结果，栈
        StringBuilder res = new StringBuilder();
        Stack<String> stack = new Stack<>();
        Boolean flag = true;    //true：第一次来
        //2. 循环遍历
        for (int i = 0; i < s.length(); i++) {
            //2.1 判断是否入栈
            if(s.charAt(i)>='0' && s.charAt(i)<='9' && flag){  //第一次来
                stack.add(""+s.charAt(i));
                flag=false;
            } else if(s.charAt(i)>='0' && s.charAt(i)<='9' && !flag){
                String pop = stack.pop();
                pop+=s.charAt(i);
                stack.add(pop);
                flag=false;
            }else if (s.charAt(i)!=']' ){
                stack.add(""+s.charAt(i));
                flag = true;
            }  else {     //2.2 入栈
                StringBuilder temp = new StringBuilder();
                while (!stack.peek().equals("[")){
                    temp.insert(0,stack.peek());
                    stack.pop();
                }
                stack.pop();
                Integer count = Integer.valueOf(stack.pop());
                String str = temp.toString();
                for (int j = 0; j < count-1; j++) {
                    temp.insert(0,str);
                }
                stack.add(temp.toString());
                flag = true;
            }
        }
        while (!stack.isEmpty()){
            res.insert(0,stack.pop());
        }
        return res.toString();

    }


}
